package com.nilhcem.fakesmtp.server;

import com.nilhcem.fakesmtp.config.ResendMailConfig;
import org.simplejavamail.api.email.EmailPopulatingBuilder;
import org.simplejavamail.api.mailer.AsyncResponse;
import org.simplejavamail.api.mailer.Mailer;
import org.simplejavamail.api.mailer.config.TransportStrategy;
import org.simplejavamail.email.EmailBuilder;
import org.simplejavamail.mailer.MailerBuilder;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;

public class ResendMailHandler {

    public static class ResendMailHandlerHolder {
        private static final ResendMailHandler INSTANCE = new ResendMailHandler();
    }

    private ResendMailConfig config;

    private Mailer mailer;

    public boolean isEnabled() {
        return enabled;
    }

    private boolean enabled = false;

    private ResendMailHandler() {

    }

    public static ResendMailHandler getInstance() {
        return ResendMailHandlerHolder.INSTANCE;
    }

    public void init(ResendMailConfig config) {
        this.config = config;
        this.enabled = true;
        this.mailer = MailerBuilder
                .withSMTPServer(config.getSmtpHost(), config.getSmtpPort(), config.getUserName(), config.getPassword())
                .withTransportStrategy(TransportStrategy.SMTPS)
                .buildMailer();
    }

    public void sendMail(String from, String fileName, String context, boolean async) {
        if (config.isEnable()) {
            // get e-mail list, map is first
            List<String> toList = config.getToMap() != null ? config.getToMap().get(from) : null;
            if (toList == null) {
                toList = config.getToList();
            }
            // list is second
            if (toList == null) {
                toList = Collections.singletonList(config.getUserName());
            }
            // create maile
            EmailPopulatingBuilder emailBuilder = EmailBuilder.startingBlank();
            emailBuilder.from(config.getUserName())
                    .to(toList.get(0))
                    .withSubject(config.getSubject())
                    .withPlainText(config.getContent())
                    .withAttachment(fileName, context.getBytes(StandardCharsets.UTF_8), "text/plain");
            // set cc when mail list is more than one
            if (toList.size() > 1) {
                toList.stream().skip(1).forEach(emailBuilder::cc);
            }
            // send mail
            this.mailer.sendMail(emailBuilder.buildEmail(), async);
        }
    }
}
